# 项目添加husky

# node 版本

使用16+的版本,npx会报Unexpected token '.',切到14+就好了

不确定是node版本问题还是项目使用了yarn的问题

# husky

添加git提交的规范限制

原理:对git执行的一些命令,通过对应的hooks钩子触发,执行自定义的脚本程序

# 安装

npm install husky -D
or
yarn add husky -D

# 初始化

如果项目已经安装过node_modules了,就手动初始化husky

npx husky-init

没安装过,就可以在package.json中加上:

"scripts": {
    "prepare": "husky install",
}

这样会在安装时自动初始化

# 添加命令

husky add .husky/pre-commit pre-commit
husky add .husky/commit-msg commit-msg

这两后面跟的都是在package.json中要执行的命令

提交前和检测commit的msg

# lint-staged

用来检查缓存区的文件

# 安装

npm install lint-staged -D
or
yarn add lint-staged -D

# 使用

在package.json 中添加以下代码

"scripts": {
    "lint-staged": "lint-staged --config lint-staged.config.js",
}

# commitlint

检查提交信息的规范

# 安装

npm install --save-dev @commitlint/config-conventional @commitlint/cli
or
yarn add @commitlint/config-conventional @commitlint/cli -D

# 使用

在package.json中scripts中添加对应脚本

"scripts": {
    "commitlint": "commitlint --config commitlint.config.js -e -V",
}

根目录添加commitlint.config.js文件

/*
  规范commit日志
  https://commitlint.js.org
*/

const types = [
  'build', // 主要目的是修改项目构建系统(例如glup,webpack,rollup的配置等)的提交
  'ci', // 修改项目的持续集成流程(Kenkins、Travis等)的提交
  'chore', // 构建过程或辅助工具的变化
  'docs', // 文档提交(documents)
  'feat', // 新增功能(feature)
  'fix', // 修复 bug
  'pref', // 性能、体验相关的提交
  'refactor', // 代码重构
  'revert', // 回滚某个更早的提交
  'style', // 不影响程序逻辑的代码修改、主要是样式方面的优化、修改
  'test', // 测试相关的开发,
],
typeEnum = {
  rules: {
    'type-enum': [2, 'always', types],
  },
  value: () => {
    return types;
  },
};

// eslint-disable-next-line no-undef
module.exports = {
  extends: ['@commitlint/config-conventional'],
  /*
  Level [0..2]: 0 disables the rule. For 1 it will be considered a warning for 2 an error.
  https://commitlint.js.org/#/reference-rules
  */
  rules: {
    'type-enum': typeEnum.rules['type-enum'],
    'subject-full-stop': [0, 'never'],
    'subject-case': [0, 'never'],
  },
};

# 效果

都弄完后,git add一些改动,commit的消息随便打,就会被拦截了